package com.tich.handler;

import com.tich.constant.ExceptionConstant;
import com.tich.exception.CommonException;
import com.tich.exception.OrderUnpaidException;
import com.tich.result.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.ErrorResponse;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.validation.FieldError;
import java.sql.SQLIntegrityConstraintViolationException;
import java.util.stream.Collectors;

/**
 * 全局异常处理奇器，处理项目中抛出的业务异常
 * */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 处理自定义业务异常
     * */
    @ExceptionHandler(CommonException.class)
    public Result<?> handleBusinessException(CommonException ex) {
        return Result.error(ex.getCode(), ex.getMessage());
    }

    @ExceptionHandler(RuntimeException.class)
    public Result<?> handleSeataWrapper(RuntimeException ex) {
        // 1. 拆出被包装的业务异常
        Throwable cause = ex.getCause();
        if (cause instanceof OrderUnpaidException) {
            OrderUnpaidException e = (OrderUnpaidException) cause;
            // 2. 取得自定义异常中的状态码和提示信息
            int statusCode = e.getCode();           // 比如 4001、5001 等自定义码
            String message = e.getMessage();        // 例如 "订单未支付"
            return Result.error(statusCode, message);
        }
        // 如果不是我们想要拆包的业务异常，就按默认逻辑返回 500
        return Result.error(ExceptionConstant.CODE_500, ExceptionConstant.SYSTEM_BUSY);
    }

    /**
     * 捕获SQL异常,此处用于抛出数据用户名重复时的错误
     * @param ex
     * @return
     * */
    @ExceptionHandler
    public Result exceptionHandler(SQLIntegrityConstraintViolationException ex){
        String message = ex.getMessage();
        if(message.contains(ExceptionConstant.SQLException)){
            return Result.error(ExceptionConstant.CODE_409, ExceptionConstant.USER_EXIST);
        }
        else {
            return Result.error(ExceptionConstant.CODE_500, ExceptionConstant.UNKNOWN_ERROR);
        }
    }

    /**
     * 处理参数校验异常（如@Validated失败）
     * */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result<?> handleValidationException(MethodArgumentNotValidException ex) {
        String errorMsg = ex.getBindingResult().getFieldErrors().stream()
                .map(FieldError::getDefaultMessage)
                .collect(Collectors.joining(", "));
        return Result.error(ExceptionConstant.CODE_400, ExceptionConstant.PARAM_ERROR + errorMsg);
    }

    /**
     * 兜底处理其他异常
     * */
    @ExceptionHandler(Exception.class)
    public Result<?> handleOtherException(Exception ex) {
        log.error("系统异常: ", ex);
        return Result.error(ExceptionConstant.CODE_500, ExceptionConstant.SYSTEM_BUSY);
    }
}